package flex.persistence {
	import flash.utils.describeType;
	import flash.utils.getDefinitionByName;

	public class Annotation {
		public static var ENTITY:String = "Entity";
		public static var TABLE:String = "Table";

		public static var COLUMN:String = "Column";

		public static var ID:String = "Id";
		public static var FLEXID:String = "FlexId";
		public static var ORDERBY:String = "OrderBy";
		public static var BASIC:String = "Basic";
		public static var TEMPORAL:String = "Temporal";
		public static var LOB:String = "Lob";
		public static var ELEMENT_COLLECTION:String = "ElementCollection";
		public static var MANY_TO_ONE:String = "ManyToOne";
		public static var MANY_TO_MANY:String = "ManyToMany";
		public static var ONE_TO_ONE:String = "OneToOne";
		public static var ONE_TO_MANY:String = "OneToMany";
		public static var TRANSIENT:String = "Triansient";

		public static var ARRAY_ELEMENT_TYPE:String = "ArrayElementType";

		public function Annotation() {
			
		}
		
		public static function getAnnotationArgumentValue(type:String, key:String):String {
			try {
				throw new Error();
			} catch(e:Error) {
				var stacktrace:String = e.getStackTrace(); 
				var line:String = stacktrace.split("	at ")[3] as String;
				var parent:String = (line.substring(0, line.indexOf("(")));
				var simpleName:String = parent.substring(parent.lastIndexOf(":") + 1);
				var nb:int = (stacktrace.split(simpleName+".mxml").length - 1) || (stacktrace.split(simpleName+".as").length - 1); 
				if(nb == 1) {				
					var classParent:Class = getDefinitionByName(parent) as Class;
					var instParent:Object = new classParent();
					var xml:XML = describeType(instParent);
					instParent = null;
					return xml.variable.metadata.(@name == type).arg.(@key == key).@value.toString();;
				}
			}
			return null
		}
		public static function getAnnotationArguments(type:String):Array {
			var array:Array = new Array();
			try {
				throw new Error();
			} catch(e:Error) {
				var stacktrace:String = e.getStackTrace(); 
				var line:String = stacktrace.split("	at ")[3] as String;
				var parent:String = (line.substring(0, line.indexOf("(")));
				var simpleName:String = parent.substring(parent.lastIndexOf(":") + 1);
				var nb:int = stacktrace.split(simpleName).length; 
				if(nb == 3) {				
					var classParent:Class = getDefinitionByName(parent) as Class;
					var instParent:Object = new classParent();
					var xml:XML = describeType(instParent);
					instParent = null;
					var annotations:XMLList = xml.variable.metadata.(@name == type);
					for each(var v:XML in annotations) {
						for each(var a:XML in v.arg) {
							array[a.@key] = a.@value;
							array.push(a.@key);
						}
						break;
					}
				}
			}
			return array;
		}
	}
}